import type { App, ObjectDirective, DirectiveBinding } from 'vue';

/**
 * 点赞放大svg动画
 * */

// 指令配置类型
interface LikePulseOptions {
  scale?: number; // 放大倍数（默认1.3）
  duration?: number; // 动画时长（毫秒，默认200）
  easing?: string; // 动画缓动函数（默认"cubic-bezier(0.17, 0.67, 0.83, 0.67)"）
}

// 默认配置
const DEFAULT_OPTIONS: LikePulseOptions = {
  scale: 1.3,
  duration: 200,
  easing: 'cubic-bezier(0.17, 0.67, 0.83, 0.67)',
};

// 注入全局样式
const injectGlobalStyles = () => {
  if (document.getElementById('v-like-pulse-styles')) return;

  const style = document.createElement('style');
  style.id = 'v-like-pulse-styles';
  style.textContent = `
    .v-like-pulse {
      transition: transform 0.5s cubic-bezier(0.17, 0.67, 0.83, 0.67);
      transform-origin: center;
      cursor: pointer;
    }
  `;
  document.head.appendChild(style);
};

// 执行放大动画
const triggerPulse = (el: any, options: LikePulseOptions) => {
  // 移除可能残留的过渡样式
  el.style.transition = 'none';
  // 重置初始状态
  el.style.transform = 'scale(1)';

  // 强制重绘
  void el.offsetWidth;

  // 应用动画样式
  el.style.transition = `transform ${options.duration}ms ${options.easing}`;
  el.style.transform = `scale(${options.scale})`;

  // 动画结束后恢复原样
  setTimeout(() => {
    el.style.transform = 'scale(1)';
  }, options.duration);
};

// 指令逻辑
const directive: ObjectDirective<SVGElement, LikePulseOptions> = {
  //@ts-ignore
  bind(el: SVGElement) {
    injectGlobalStyles();
  },

  mounted(el: SVGElement, binding: DirectiveBinding<LikePulseOptions>) {
    const options = { ...DEFAULT_OPTIONS, ...binding.value };

    // 添加基础类名
    el.classList.add('v-like-pulse');

    // 点赞点击事件处理
    const handleClick = () => {
      // 触发放大动画
      triggerPulse(el, options);

      // 如果有绑定回调函数，执行回调
      //@ts-ignore
      if (typeof binding.value?.onLike === 'function') {
        //@ts-ignore
        binding.value.onLike();
      }
    };

    // 绑定点击事件
    el.addEventListener('click', handleClick);

    // 存储数据供后续使用
    (el as any).vLikePulseData = {
      options,
      handler: handleClick,
    };
  },

  updated(el: SVGElement, binding: DirectiveBinding<LikePulseOptions>) {
    if (!binding.value) return;

    const data = (el as any).vLikePulseData;
    if (!data) return;

    // 更新配置
    data.options = { ...data.options, ...binding.value };
  },

  unmounted(el: SVGElement) {
    const data = (el as any).vLikePulseData;
    if (data) {
      // 移除事件监听
      el.removeEventListener('click', data.handler);
      // 清理样式和类名
      el.classList.remove('v-like-pulse');
      el.style.transform = '';
      el.style.transition = '';
      delete (el as any).vLikePulseData;
    }
  },
};

// 全局注册指令
export const setupLikePulseDirective = (app: App) => {
  app.directive('like-pulse', directive);
};

export default directive;
